<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>本地的H5页面</title>
</head>

<body>
    <h1>本地的H5页面</h1>
    <button onclick="sendMessageToNative()">发送消息给原生</button>
    <div id="myDiv" style="line-height: 40px;"></div>
    <script>
        const TRANSMIT_PORT_KEY = 'transmit_port_key';
        let currentPort = null;
        window.addEventListener('message', function (event) {
            if (event.data === TRANSMIT_PORT_KEY) {
                // 获取原生传递过来的端口
                currentPort = event.ports[0];
                if (!currentPort) {
                    // return alert('接收端口失败');
                }
                // alert('接收端口成功');

                getTimeFromNative();
            }
        });

        /** 获取原生传递过来的时间 */
        function getTimeFromNative() {
            // [native -> h5] 端口监听native的消息
            currentPort.onmessage = function (event) {
                const res = JSON.parse(event.data);
                if (res.type === 'native-time') {
                    document.getElementById('myDiv').innerText = res.data;
                }
            };
        }

        /** 发送消息给原生 */
        function sendMessageToNative() {
            if (!currentPort) {
                // return alert('未获取到端口');
                return;
            }
            // [h5 -> native] 端口发送消息给native
            currentPort.postMessage(JSON.stringify({ type: 'h5-time', data: Date.now() }));
        }
    </script>
</body>

</html>